using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Windows.Forms;

namespace ctsu.Admin.Forms
{
	public partial class QaReports : Form
	{
		enum AgeType
		{
			start,
			end,
		}

		enum ParameterType
		{
			sql,
			reportingServices
		}

		public QaReports()
		{
			InitializeComponent();
		}

		private void QaReports_Load(object sender, EventArgs e)
		{
			FillCombos();
			btnClearCommon_Click(null, EventArgs.Empty);
		}

		private void FillCombos()
		{
			FillProtocol();
			Forms.Utils.LoadCbo(PainScale, "PainScale_L", true);
			Forms.Utils.LoadCbo(SampleCollection, "SampleCollection_L", true);
		}

		private void FillPainScale()
		{
			string sql = "SELECT * FROM vwQaDistinctProtocols";
			IDataReader reader = null;
			NameVal nv;
			ArrayList al = new ArrayList();

			try
			{
				reader = Data.DataAccess.GetDataReader(sql);
				Protocol.BeginUpdate();

				string sVal;
				int iVal;
				while (reader.Read())
				{
					if (reader.IsDBNull(0))
						continue;
					sVal = reader.GetString(1);

					iVal = reader.GetInt32(0);

					Console.WriteLine("Val:" + iVal);
					nv = new NameVal(iVal, sVal);
					al.Add(nv);
				}


				nv = new NameVal(-1, "All");
				al.Insert(0, nv);


				Protocol.DataSource = al;
				Protocol.DisplayMember = "Name";
				Protocol.ValueMember = "Val";
				Protocol.EndUpdate();
			}
			catch
			{
				throw;
			}
			finally
			{
				if (reader != null)
					reader.Close();
			}
		}

		private void FillProtocol()
		{
			string sql = "SELECT * FROM vwQaDistinctProtocols";
			IDataReader reader = null;
			NameVal nv;
			ArrayList al = new ArrayList();

			try
			{
				reader = Data.DataAccess.GetDataReader(sql);
				Protocol.BeginUpdate();

				string sVal;
				int iVal;
				while (reader.Read())
				{
					if (reader.IsDBNull(0))
						continue;
					sVal = reader.GetString(1);

					iVal = reader.GetInt32(0);

					Console.WriteLine("Val:" + iVal);
					nv = new NameVal(iVal, sVal);
					al.Add(nv);
				}


				nv = new NameVal(-1, "All");
				al.Insert(0, nv);


				Protocol.DataSource = al;
				Protocol.DisplayMember = "Name";
				Protocol.ValueMember = "Val";
				Protocol.EndUpdate();
			}
			catch
			{
				throw;
			}
			finally
			{
				if (reader != null)
					reader.Close();
			}
		}

		private void btnClearCommon_Click(object sender, EventArgs e)
		{
			Protocol.SelectedValue = -1;
			StartDate.IsNullDate = true;
			EndDate.IsNullDate = true;

			//clear any mult-selections
			Age.SelectedIndex = -1;
			Age.SelectedIndex = 0;
		}

		private void RunIVReport(object sender, EventArgs e)
		{
			if (!CreateIvTempTable())
				return;
			string url = Properties.Settings.Default.Crema2_ReportingServices_ReportingService.ToString().Trim();
			string server = GetServerFromUrl(url);
			StringBuilder sb = new StringBuilder("http://" + server + "/reportserver?");
			sb.Append("/GCRC/GCRCAdmin/Qa+Iv+Stick+Audit&rs:Command=Render");
			System.Diagnostics.Process.Start(sb.ToString());
		}

		private void btnRunAveStick_Click(object sender, EventArgs e)
		{
			if (!CreateIvTempTable())
				return;

			string url = Properties.Settings.Default.Crema2_ReportingServices_ReportingService.ToString().Trim();
			string server = GetServerFromUrl(url);
			StringBuilder sb = new StringBuilder("http://" + server + "/reportserver?");
			sb.Append("/GCRC/GCRCAdmin/Qa+Iv+Stick+Audit+Average+Sticks&rs:Command=Render");
			System.Diagnostics.Process.Start(sb.ToString());
		}

		private void btnRunAvePain_Click(object sender, EventArgs e)
		{
			if (!CreateIvTempTable())
				return;
			string url = Properties.Settings.Default.Crema2_ReportingServices_ReportingService.ToString().Trim();
			string server = GetServerFromUrl(url);
			StringBuilder sb = new StringBuilder("http://" + server + "/reportserver?");
			sb.Append("/GCRC/GCRCAdmin/Qa+Iv+Stick+Audit+Average+Pain&rs:Command=Render");
			System.Diagnostics.Process.Start(sb.ToString());
		}

		private bool CreateIvTempTable()
		{
			StringBuilder sql = new StringBuilder("INSERT INTO aaIvAuditReport(ProtocolNumber, Qid, VisitDate, Patient, IvAudit, Sticks, PainScore, " +
				"PainScaleName, Recovery, PiuNothing, PiuPharmacologic, PiuBehavioral, PiuOther, OtherTechnique, q.SampleCollectionName) " +
				"SELECT q.ProtocolNumber, q.ID, q.VisitDate, q.Patient, q.IvAudit, q.Sticks, q.PainScore, q.PainScaleName, " +
				"q.Recovery, q.PiuNothing, q.PiuPharmacologic, q.PiuBehavioral, q.PiuOther, q.OtherTechnique, q.SampleCollectionName " +
				"FROM dbo.vwQa2PatientProtocol AS q WHERE q.IvAudit");
			if (rdoBoth.Checked)
				sql.Append(">0");
			else if (rdoIV.Checked)
				sql.Append("=1");
			else if (rdoPhlebotomy.Checked)
				sql.Append("=2");

			GetCommonCriteria(sql);

			if (!GetIvStickCriteria(sql))
				return false;

			string sConn = ConfigurationManager.ConnectionStrings["CreamConnectString"].ToString();
			SqlConnection conn = new SqlConnection(sConn);

			try
			{
				//truncate temp table 
				SqlCommand cmd = new SqlCommand("TRUNCATE TABLE aaIvAuditReport", conn);
				conn.Open();
				cmd.ExecuteNonQuery();

				cmd = new SqlCommand(sql.ToString(), conn);
				cmd.ExecuteNonQuery();


				return true;
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message);
				return false;
			}
			finally
			{
				conn.Dispose();
			}
		}

		private bool GetIvStickCriteria(StringBuilder sql)
		{
			if (chkU1.Checked)
				sql.Append(" AND " + chkU1.Tag.ToString());

			if (chkU2.Checked)
				sql.Append(" AND " + chkU2.Tag.ToString());

			if (chkU3.Checked)
				sql.Append(" AND " + chkU3.Tag.ToString());

			if (chkU4.Checked)
			{
				if (PainScale.SelectedIndex < 1)
				{
					MessageBox.Show("You must select a 'Pain Scale' criteria!", "Criteral Missing", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
					return false;
				}
				sql.Append(" AND " + chkU4.Tag.ToString());
			}

			if (chkU5.Checked)
			{
				if (SampleCollection.SelectedIndex < 1)
				{
					MessageBox.Show("You must select a 'Sample Collection' criteria!", "Criteral Missing", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
					return false;
				}
				sql.Append(" AND " + chkU5.Tag.ToString());
			}
			return true;

		}

		private void GetCommonCriteria(StringBuilder sql)
		{
			if (Protocol.SelectedItem != null)
			{
				int proto = (int)Protocol.SelectedValue;
				if (proto > 0)
				{
					sql.Append(" AND q.ProtocolID=" + proto);
				}
			}

			if (!StartDate.IsNullDate)
			{
				sql.Append(" AND q.VisitDate>='" + StartDate.Value.ToShortDateString() + "'");
				if (!EndDate.IsNullDate)
					sql.Append(" AND q.VisitDate<='" + EndDate.Value.ToShortDateString() + "'");
			}

			sql.Append(GetAgeParameters(ParameterType.sql));
		}

		private void Protocol_SelectedIndexChanged(object sender, EventArgs e)
		{

		}

		private void chkAll_CheckedChanged(object sender, EventArgs e)
		{
			if (chkAll.Checked)
			{
				chk1.Checked = false;
				chk2.Checked = false;
				chk3.Checked = false;
				chk4.Checked = false;
			}
		}

		private void chk_CheckedChanged(object sender, EventArgs e)
		{
			CheckBox chk = (CheckBox)sender;
			if (chk.Checked)
				chkAll.Checked = false;
		}

		private void btnRunDCReport_Click(object sender, EventArgs e)
		{
			string url = Properties.Settings.Default.Crema2_ReportingServices_ReportingService.ToString().Trim();
			string server = GetServerFromUrl(url);
			StringBuilder sb = new StringBuilder("http://" + server + "/reportserver?");
			sb.Append("/GCRC/GCRCAdmin/Qa+Problems+Grouped&rs:Command=Render");

			//get protocol parameter
			int protocol = (int)Protocol.SelectedValue;
			if (protocol > -1)
				sb.Append("&protocol=" + protocol);

			DateTime start = DateTime.Parse("03/12/1924");
			if (!StartDate.IsNullDate)
				start = StartDate.Value;
			sb.Append("&startDate=" + start.ToShortDateString());

			DateTime end = DateTime.Parse("03/12/2024");
			if (!EndDate.IsNullDate)
				end = EndDate.Value;
			sb.Append("&endDate=" + end.ToShortDateString());

			//age
			string age = GetAgeParameters(ParameterType.reportingServices);
			sb.Append(age);

			//groups
			string groups = GetGroupParameters();
			sb.Append(groups);

			System.Diagnostics.Process.Start(sb.ToString());
		}

		private string GetGroupParameters()
		{
			StringBuilder sb = new StringBuilder();

			if (chkAll.Checked)
				return "&group1=1&group2=2&group3=3&group4=4";

			//1
			if (chk1.Checked && (!chk2.Checked) && (!chk3.Checked) && (!chk4.Checked))
				return "&group1=1&group2=1&group3=1&group4=1";
			//1,2
			if (chk1.Checked && chk2.Checked && (!chk3.Checked) && (!chk4.Checked))
				return "&group1=1&group2=2&group3=2&group4=2";
			//1,2,3
			if (chk1.Checked && chk2.Checked && chk3.Checked && (!chk4.Checked))
				return "&group1=1&group2=2&group3=3&group4=3";
			// 1,2,3,4
			if (chk1.Checked && chk2.Checked && chk3.Checked && chk4.Checked)
				return "&group1=1&group2=2&group3=3&group4=4";
			// 1,2,4
			if (chk1.Checked && chk2.Checked && (!chk3.Checked) && chk4.Checked)
				return "&group1=1&group2=2&group3=2&group4=4";
			//1,3
			if (chk1.Checked && (!chk2.Checked) && chk3.Checked && (!chk4.Checked))
				return "&group1=1&group2=3&group3=3&group4=3";
			//1,3,4
			if (chk1.Checked && (!chk2.Checked) && chk3.Checked && chk4.Checked)
				return "&group1=1&group2=3&group3=3&group4=4";
			//1,4
			if (chk1.Checked && (!chk2.Checked) && (!chk3.Checked) && chk4.Checked)
				return "&group1=1&group2=1&group3=1&group4=4";

			//2
			if ((!chk1.Checked) && chk2.Checked && (!chk3.Checked) && (!chk4.Checked))
				return "&group1=2&group2=2&group3=2&group4=2";
			//2,3
			if ((!chk1.Checked) && chk2.Checked && chk3.Checked && (!chk4.Checked))
				return "&group1=2&group2=2&group3=3&group4=3";
			//2,3,4
			if ((!chk1.Checked) && chk2.Checked && chk3.Checked && chk4.Checked)
				return "&group1=2&group2=2&group3=3&group4=4";
			//2,4
			if ((!chk1.Checked) && chk2.Checked && (!chk3.Checked) && chk4.Checked)
				return "&group1=2&group2=2&group3=2&group4=4";
			//3
			if ((!chk1.Checked) && (!chk2.Checked) && chk3.Checked && (!chk4.Checked))
				return "&group1=3&group2=3&group3=3&group4=3";
			//3,4
			if ((!chk1.Checked) && (!chk2.Checked) && chk3.Checked && chk4.Checked)
				return "&group1=3&group2=3&group3=3&group4=4";
			//4
			if ((!chk1.Checked) && (!chk2.Checked) && (!chk3.Checked) && chk4.Checked)
				return "&group1=4&group2=4&group3=4&group4=4";

			return "";

		}

		private string GetAgeParameters(ParameterType pt)
		{
			string retVal = "";
			decimal start = 0;
			decimal end = 150;

			if (Age.SelectedIndices.Count == 1)
			{
				if (Age.SelectedIndices[0] > 0)
				{
					start = GetAge(Age.SelectedIndices[0], AgeType.start);
					end = GetAge(Age.SelectedIndices[0], AgeType.end);
				}
			}

			if (Age.SelectedIndices.Count > 1)
			{
				if (Age.SelectedIndices[0] > 0)
				{
					start = GetAge(Age.SelectedIndices[0], AgeType.start);
					end = GetAge(Age.SelectedIndices[Age.SelectedIndices.Count - 1], AgeType.end);
				}
			}

			if (pt == ParameterType.reportingServices)
				retVal = "&startAge=" + start.ToString() + "&endAge=" + end.ToString();
			else
				retVal = " AND (q.Age>=" + start.ToString() + " AND q.Age<=" + end.ToString() + ")";
			return retVal;
		}

		private decimal GetAge(int i, AgeType ageType)
		{
			decimal retVal = 0;
			switch (i)
			{
				case 1:
					if (ageType == AgeType.start)
						retVal = 0;
					else
						retVal = .12M;
					break;
				case 2:
					if (ageType == AgeType.start)
						retVal = .12M;
					else
						retVal = 1;
					break;
				case 3:
					if (ageType == AgeType.start)
						retVal = 1;
					else
						retVal = 3;
					break;
				case 4:
					if (ageType == AgeType.start)
						retVal = 3;
					else
						retVal = 6;
					break;
				case 5:
					if (ageType == AgeType.start)
						retVal = 6;
					else
						retVal = 12;
					break;
				case 6:
					if (ageType == AgeType.start)
						retVal = 12;
					else
						retVal = 18;
					break;
				case 7:
					if (ageType == AgeType.start)
						retVal = 18;
					else
						retVal = 150;
					break;
			}
			return retVal;
		}

		private string GetServerFromUrl(string url)
		{
			int pos1 = url.IndexOf("//");
			int pos2 = url.IndexOf("/", pos1 + 2);

			string retVal = url.Substring(pos1 + 2, (pos2 - pos1) - 2);
			return retVal;
		}

		private void chkU1_CheckedChanged(object sender, EventArgs e)
		{
			CheckBox cb = (CheckBox)sender;
			if (cb.Checked)
				Sticks.Enabled = true;
			else
			{
				Sticks.Value = 0;
				Sticks.Enabled = false;
			}
		}

		private void chkU2_CheckedChanged(object sender, EventArgs e)
		{
			CheckBox cb = (CheckBox)sender;
			if (cb.Checked)
				PainScore.Enabled = true;
			else
			{
				PainScore.Value = 0;
				PainScore.Enabled = false;
			}
		}

		private void chkU3_CheckedChanged(object sender, EventArgs e)
		{
			CheckBox cb = (CheckBox)sender;
			if (cb.Checked)
				Recovery.Enabled = true;
			else
			{
				Recovery.Value = 0;
				Recovery.Enabled = false;
			}
		}

		private void chkU4_CheckedChanged(object sender, EventArgs e)
		{
			CheckBox cb = (CheckBox)sender;
			if (cb.Checked)
				PainScale.Enabled = true;
			else
			{
				PainScale.SelectedIndex = -1;
				PainScale.Enabled = false;
			}
		}

		private void chkU5_CheckedChanged(object sender, EventArgs e)
		{
			CheckBox cb = (CheckBox)sender;
			if (cb.Checked)
				SampleCollection.Enabled = true;
			else
			{
				SampleCollection.SelectedIndex = -1;
				SampleCollection.Enabled = false;
			}
		}

		private void btnClrIv_Click(object sender, EventArgs e)
		{
			chkU1.Checked = false;
			chkU2.Checked = false;
			chkU3.Checked = false;
			chkU4.Checked = false;
			chkU5.Checked = false;

			Sticks.Value = 0;
			Sticks.Enabled = false;
			PainScore.Value = 0;
			PainScore.Enabled = false;
			Recovery.Value = 0;
			Recovery.Enabled = false;
			PainScale.SelectedIndex = -1;
			PainScale.Enabled = false;
			SampleCollection.SelectedIndex = -1;
			SampleCollection.Enabled = false;
		}

		private void Sticks_ValueChanged(object sender, EventArgs e)
		{
			chkU1.Tag = " Sticks >= " + Sticks.Value;
		}

		private void PainScore_ValueChanged(object sender, EventArgs e)
		{
			chkU2.Tag = " PainScore >= " + PainScore.Value;
		}

		private void Recovery_ValueChanged(object sender, EventArgs e)
		{
			chkU3.Tag = " Recovery >= " + Recovery.Value;
		}

		private void PainScale_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (PainScale.SelectedIndex > 0)
				chkU4.Tag = " PainScale = " + PainScale.SelectedValue.ToString();
		}

		private void SampleCollection_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (SampleCollection.SelectedIndex > 0)
				chkU5.Tag = " SampleCollection = " + SampleCollection.SelectedValue.ToString();
		}

	}
}